import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式: light, dark, auto
  const themeMode = ref<'light' | 'dark' | 'auto'>('auto')
  
  // 初始化主题
  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | 'auto' | null
    if (savedTheme) {
      themeMode.value = savedTheme
    }
    
    applyTheme()
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
      if (themeMode.value === 'auto') {
        applyTheme()
      }
    })
  }
  
  // 应用主题
  const applyTheme = () => {
    let isDark = false
    
    if (themeMode.value === 'auto') {
      isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    } else {
      isDark = themeMode.value === 'dark'
    }
    
    if (isDark) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 切换主题
  const toggleTheme = (mode: 'light' | 'dark' | 'auto') => {
    themeMode.value = mode
    localStorage.setItem('theme', mode)
    applyTheme()
  }
  
  // 监听主题变化
  watch(themeMode, () => {
    applyTheme()
  })
  
  return { themeMode, initTheme, toggleTheme, applyTheme }
})